using System;
using System.Web;
using System.Web.Mail;
using System.Xml;
using System.Diagnostics;
using System.Drawing;
using System.Reflection;
using System.IO;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Web.Core;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Net;


namespace newtelligence.DasBlog.Web.Services
{
	/// <summary>
	/// Summary description for CrosspostReferrerHandler.
	/// </summary>
    public partial class WebWebServices
	{
        static byte[] crosspostBitmap;

        static void EnsureInitCrosspost()
        {
            if ( crosspostBitmap == null )
            {
                Assembly asm = Assembly.GetExecutingAssembly();
                
                using ( Stream stm = asm.GetManifestResourceStream(asm.GetName().Name+".aggbug.gif") )
                {
                    crosspostBitmap = new byte[stm.Length];
                    stm.Read(crosspostBitmap,0,(int)stm.Length);
                }
            }
        }

		[OperationContract, WebGet(UriTemplate="/crosspost?id={sourceId}")]
        public Stream CrosspostReferrerHandler( string sourceId )
        {
            EnsureInitCrosspost();
                          
            string referrerUrl;

            /*
             * This service is a bit diffent from the other handlers, because 
             * the "bugs" are out in the wild regardless of whether the service is
             * enabled. So the service must yield a valid result, regardless of
             * whetr
             */
            if ( siteConfig.EnableCrossposts )
            {
                referrerUrl = WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.Referer];
                                
                try
                {
                    Entry entry = dataService.GetEntry( sourceId );
                    if ( entry != null )
                    {
                        // we'll check whether the entry exists just to avoid trash in the DB
                        loggingService.AddCrosspostReferrer(
                            new LogDataItem(
							Utils.GetPermaLinkUrl(siteConfig, sourceId),referrerUrl,WebOperationContext.Current.IncomingRequest.Headers[HttpRequestHeader.UserAgent], HttpContext.Current.Request.UserHostName));
                    }
					else
                    {
						StackTrace st = new StackTrace();
						loggingService.AddEvent(new EventDataItem(EventCodes.Error, "Entry was not found: " + sourceId + " " + st.ToString(), ""));
                    }
                }
                catch( Exception exc )
                {
                    // absorb
                    ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,exc);
                }
            }

            WebOperationContext.Current.OutgoingResponse.ContentType = "image/gif";
            WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.OK;

            return new MemoryStream(crosspostBitmap);
        }
	}
}
